using UnityEngine;
using UnityEngine.InputSystem;

namespace Player
{
    public class Sign : MonoBehaviour
    {
        private PlayerInputControl _playerInput;
        private Animator _anim;
        public Transform playerTrans;
        public GameObject signSprite;
        private IInteractable _targetItem;
        private bool _canPress;
        private SpriteRenderer _spriteRenderer;

        private void Start()
        {
            _spriteRenderer = signSprite.GetComponent<SpriteRenderer>();
        }

        private void Awake()
        {
            // anim = GetComponentInChildren<Animator>();
            _anim = signSprite.GetComponent<Animator>();
            _playerInput = new PlayerInputControl();
            _playerInput.Enable();
        }

        private void OnEnable()
        {
            InputSystem.onActionChange += OnActionChange;
            _playerInput.Gameplay.Confirm.started += OnConfirm;
        }

        private void OnDisable()
        {
            _canPress = false;
        }

        private void Update()
        {
            _spriteRenderer.enabled = _canPress;
            signSprite.transform.localScale = playerTrans.localScale;
        }

        private void OnConfirm(InputAction.CallbackContext context)
        {
            if (_canPress)
            {
                _targetItem.TriggerAction();
            }
        }

        /// <summary>
        /// 切换设备同时切换动画
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="actionChange"></param>
        private void OnActionChange(object obj, InputActionChange actionChange)
        {
            // if (actionChange == InputActionChange.ActionStarted)
            // {
            //     //Debug.Log(((InputAction)obj).activeControl.device);
            //
            //     var d = ((InputAction)obj).activeControl.device;
            //
            //     switch (d.device)
            //     {
            //         case Keyboard:
            //             anim.Play("keyboard");
            //             break;
            //         case DualShockGamepad:
            //             anim.Play("ps");
            //             break;
            //     }
            // }
        }

        private void OnTriggerStay2D(Collider2D collision)
        {
            if (collision.CompareTag("Interactable"))
            {
                _canPress = true;
                _targetItem = collision.GetComponent<IInteractable>();
            }
        }

        private void OnTriggerExit2D(Collider2D collision)
        {
            _canPress = false;
        }
    }
}